<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Axios 二次封装</title>
  <link crossorigin="anonymous" href="https://cdn.bootcss.com/nprogress/0.2.0/nprogress.css" rel="stylesheet">
  <script crossorigin="anonymous" src="https://cdn.bootcss.com/nprogress/0.2.0/nprogress.js"></script>
  <script crossorigin="anonymous" src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
</head>

<body>
  <!-- 
    测试接口1: https://api.github.com/search/repositories?q=v&sort=stars
    测试接口1: https://api.github.com/search/users?q=v
  -->
  <!--
   1). 统一进行请求配置: 基础路径/超时时间等
   2). 请求过程中loading提示
   3). 请求可能需要携带token数据
   4). 请求成功的value不再是response, 而是response.data
   5). 请求失败/出错统一进行处理, 每个请求可以不用单独处理
  -->
  <div>
    <button onclick="getUsers()">获取用户列表</button>
    <button onclick="getRepos()">获取仓库列表</button>
  </div>
  <script>
        // axios 基础配置
        axios.defaults.baseURL = 'https://api.github.com';
        axios.defaults.timeout = 3000;
        // 请求拦截器
        axios.interceptors.request.use(config => {
            // 开始loading
            NProgress.start();
            // 配置 token
            // config.pramas = {x:1,y:2}
            // config.headers.token = 'sdjfsldkj'
            return config;
        },error => {
        
            return Promise.reject(error);
        });

        // 响应拦截器
        axios.interceptors.response.use(response=>{
            NProgress.done();
            return response.data;
        },error=>{
            // 打印失败
            console.log(error);
            return new Promise(()=>{});
        })

        function getUsers(){
            axios({
                url:'/search/repositories?q=v&sort=stars',
                method:'get'
            }).then(response=>{
                console.log(response);
            })
        }
  </script>

</body>

</html>